<?php
if (! defined ('IN_ZWS')) exit ();

class IAction extends PublicAction {
	function index() {
		$this -> assign('leftNav', 0);
		$mood = D('MoodView'); //实例化Comment视图模型
		$zoneMoods = $mood -> where(array('uid' => $_SESSION['uid'], 'pid' => 0)) -> limit(10) -> order('ctime desc') -> select(); //将一级评论查询出来
		foreach($zoneMoods as $zoneMood) {
			$moods[$zoneMood['id']] = $zoneMood; //将查询出来的一级评论按id赋给comments数组
		}
		$moodID = array_keys($moods); //取出一级评论的id，为下面查询对应的二级评论做准备
		if (!isEmpty($moodID)) {
			foreach($moodID as $id) {
				$sqlArray[] = 'pid=' . $id; //生成查询二级评论所用条件数组
			}
			$sql = implode(' OR ', $sqlArray); //将数组连接，生成对应的SQL条件语句
			$zoneMoods = $mood -> where($sql) -> limit(10) -> order('ctime desc') -> select(); //查询对应二级评论
			foreach($zoneMoods as $zoneMood) {
				$moods[$zoneMood['pid']]['comments'][$zoneMood['id']] = $zoneMood; //按树形排列评论
				$applaudMoodID[] = $zoneMood['id'];
			}
			$applaudMoodID = array_merge($commentID, $applaudMoodID); //取出一二级评论的ID
			$applaud = D('MoodApplaudView'); //实例化CommentApplaud视图模型
			unset($sqlArray); //将之前的sql合并前数组销毁
			foreach($applaudMoodID as $id) {
				$sqlArray[] = 'ZoneMood.id=' . $id; //生成新的用于合并的id子条件数组
			}
			$sql = implode(' OR ', $sqlArray); //生成新的sql条件字句
			$applaudArray = $applaud -> where($sql) -> select(); //找出各评论的赞
			foreach($applaudArray as $applaudId) {
				$applauds[$applaudId['id']][] = $applaudId['uid']; //将找出来的信息按评论ID分组
			}
		}
		$this -> assign('applauds', $applauds);
		$this -> assign('moods', $moods);
		$this -> display();
	}

	function message() {
		$this -> assign('leftNav', 1);
		$this -> display();
	}

	function comment() {
		$this -> assign('leftNav', 2);
		$this -> display();
	}

	function history() {
		$this -> assign('leftNav', 3);
		$this -> display();
	}

	function fav() {
		$this -> assign('leftNav', 4);
		$this -> display();
	}

	function setting() {
		$this -> assign('leftNav', 5);
		$this -> display();
	}

	function addMood() {
		if (checkQuick(10)) $this -> ajaxReturn('', '发言速度过快', 1);
		$addMood = D('AddMood');
		if ($addMood -> create()) {
			if ($addMood -> add()) {
				$this -> ajaxReturn('', '发表成功', 0);
			} else {
				$this -> ajaxReturn('', $addMood -> getError(), 1);
			}
		} else {
			$this -> ajaxReturn('', $addMood -> getError(), 1);
		}
	}

	function doApplaud() {
		$cid = intval($this -> _post('cid'));
		if (!$cid) $this -> ajaxReturn('', '非法操作！', 1);
		$M = M('ZoneApplaud');
		if ($M -> add(array('uid' => $_SESSION['uid'], 'cid' => $cid, 'ctime' => time()))) {
			$count = $M -> where('cid=' . $cid) -> count();
			$this -> ajaxReturn(array('count' => $count), '成功', 0);
		} else {
			$count = $M -> where('cid=' . $cid) -> count();
			if ($M -> where('cid=' . $cid . ' AND uid=' . $_SESSION['uid']) -> find()) $this -> ajaxReturn(array('count' => $count), '您已赞过', 1);
			$this -> ajaxReturn(array('count' => $count), '未知错误', 2);
		}
	}

	function delMood() {
		$cid = intval($this -> _post('cid'));
		if (!$cid) $this -> ajaxReturn('', '非法操作！', 1);
		$M = M('ZoneMood');
		if ($M -> where('id=' . $cid . ' AND uid=' . $_SESSION['uid']) -> delete()) $this -> ajaxReturn('', '删除成功', 0);
		$this -> ajaxReturn('', '非法操作！', 1);
	}

	function saveSetting() {
		$info = D('InfoUpdate');
		if (!isEmpty($_POST['avatar'])) unset($_POST['avatar']); //防止意外更新头像
		if ($info -> create()) {
			if ($info -> where("uid=" . $_SESSION['uid']) -> save() !== false) {
				$this -> ajaxReturn('', '保存成功', 0);
			} else {
				$this -> ajaxReturn('', $info -> getError(), 1);
			}
		} else {
			$this -> ajaxReturn('', $info -> getError(), 1);
		}
	}

	function uploadAvatar() {
		if (!isEmpty($_SESSION['tas'])) {
			unlink($_SESSION['tas']);
			unset($_SESSION['tas']);
		}
		import('ORG.Net.UploadFile');
		$upload = new UploadFile();
		$upload -> maxSize = 1 * 1024 * 1024;
		$upload -> allowExts = array('jpg', 'png', 'gif');
		$upload -> uploadReplace = true;
		$upload -> saveRule = 'getAvatarName';
		$path = "./Public/upload/avatar/";
		$upload -> savePath = $path;
		if (!$upload -> upload()) {
			$this -> ajaxReturn('', $upload -> getErrorMsg(), 1);
		} else {
			$info = $upload -> getUploadFileInfo();
			$tempSrc = $info[0]['savepath'] . $info[0]['savename'];
			$tempSize = getimagesize($tempSrc);
			if ($tempSize[0] < 100 || $tempSize[1] < 100) {
				unlink($tempSrc);
				$this -> ajaxReturn(0, '图片长与宽均不得低于100像素！', 1);
			}
			$_SESSION['tas'] = $tempSrc; //Temp Avatar Src
			$this -> ajaxReturn($info[0], '上传成功！', 0);
		}
	}

	function delUploadedAvatar() {
		if (!isEmpty($_SESSION['tas'])) {
			unlink($_SESSION['tas']);
			unset($_SESSION['tas']);
			$this -> ajaxReturn('', '删除成功！', 0);
		}
		$this -> ajaxReturn('', '非法操作！', 1);
	}

	function cropAvatar() {
		global $userInfo;
		if (isEmpty($_SESSION['tas'])) $this -> ajaxReturn('', '非法操作！', 1);
		$params = $this -> _post();
		if (!isset($params) && isEmpty($params)) {
			return;
		}
		$tempSrc = $_SESSION['tas'];
		$saveDir = dirname($tempSrc) . '/';
		$saveName = substr(substr(basename($tempSrc), 3), 0, strrpos(substr(basename($tempSrc), 3), '.'));
		$saveSuffix = end(explode('.', $tempSrc));
		$saveSrc = $saveDir . $saveName . '.' . $saveSuffix;
		import('ORG.Util.Image.ThinkImage');
		$avatar = new ThinkImage(THINKIMAGE_GD);
		$avatar -> open($tempSrc) -> crop($params['w'], $params['h'], $params['x'], $params['y']) -> save($saveSrc);
		$avatar -> open($saveSrc) -> thumb(300, 300, 1) -> save($saveDir . $saveName . '_300.' . $saveSuffix);
		$avatar -> open($saveSrc) -> thumb(100, 100, 1) -> save($saveDir . $saveName . '_100.' . $saveSuffix);
		$avatar -> open($saveSrc) -> thumb(50, 50, 1) -> save($saveDir . $saveName . '_50.' . $saveSuffix);
		switch ($saveSuffix) {
			case 'jpg':
				$suffixType = 0;
				break;
			case 'png':
				$suffixType = 1;
				break;
			case 'gif':
				$suffixType = 2;
				break;
		}
		$user = M('UserInfo');
		if ($user -> where('uid=' . $_SESSION['uid']) -> save(array('avatar' => $suffixType . $saveName))) {
			unset($_SESSION['tas']);
			unlink($tempSrc);
			unlink($saveSrc);
			if (basename($userInfo['avatar'][300]) != 'noavatar_300.jpg') {
				unlink('./' . $userInfo['avatar'][300]);
				unlink('./' . $userInfo['avatar'][100]);
				unlink('./' . $userInfo['avatar'][50]);
			}
			$this -> ajaxReturn(array('redirect' => __URL__ . '/setting'), '上传头像成功，2秒后将自动刷新本页面', 0);
		}
		$this -> ajaxReturn('', '保存失败', 1);
	}

	function changePwd() {
		global $userInfo;
		if ($userInfo['password'] == md5(md5($this -> _post('currentPassword')) . $userInfo['salt'])) {
			if ($this -> _post('newPassword') == $this -> _post('currentPassword')) $this -> ajaxReturn('', '新密码不能与原密码相同！', 1);
			$user = D('ChangePwd');
			if ($user -> create()) {
				$userData = $user -> getData();
				$data = array('password' => $userData['password'],
					'salt' => $userData['salt'],
					'cptime' => $userData['cptime'],
					);
				$info = D('User');
				$log = array('uid' => $_SESSION['uid'],
					'type' => 3,
					'status' => 1,
					'time' => $userData['cptime'],
					'ip' => $_SERVER['REMOTE_ADDR'],
					);
				if ($info -> where('id=' . $_SESSION['uid']) -> save($data)) {
					$info -> table('zws_user_log') -> add($log);
					$this -> ajaxReturn(array('redirect' => __APP__ . '/u/login', 'relay' => 3000), '修改成功，3秒后稍后将跳转到登录页面，请重新登录', 0);
				} else {
					$this -> ajaxReturn('', $info -> getError(), 1);
				}
			} else {
				$this -> ajaxReturn('', $user -> getError(), 1);
			}
		} else {
			$this -> ajaxReturn('', '原密码错误，请重新输入！', 1);
		}
	}

	function changeMail() {
		global $userInfo;
		$reSend = false;
		$newMail = $this -> _post('newMail');
		if (!isEmpty($newMail)) {
			if ($newMail == $userInfo['email']) $this -> ajaxReturn('', '新邮箱不能与当前邮箱相同！', 1);
			$user = M ('User');
			$verify = M ('UserVerify');
			if ($user -> where(array('email' => $newMail)) -> find()) $this -> ajaxReturn('', '该邮箱已被占用，请更换邮箱！', 1);
			import ('ORG.Util.String');
			$authcode = String :: randString (64);
			$findVerify = $verify -> where(array('email' => $newMail)) -> find();
			if ($findVerify) {
				$findVerifyData = json_decode($findVerify['data'], true);
				if ($findVerify['username'] == $userInfo['email'] || $findVerifyData['oldMail'] == $userInfo['email']) {
					$reSend = true;
				} else {
					$this -> ajaxReturn('', '该邮箱已被占用，请更换邮箱', 1);
				}
			}
			$verifyInfo = array('username' => $userInfo['username'],
				'email' => $newMail,
				'type' => 3,
				'authcode' => $authcode,
				'data' => json_encode(array('oldMail' => $userInfo['email'], 'step' => 0)),
				'time' => time(),
				);
			if ($reSend == true) {
				dump($verify -> where(array('id' => $findVerify['id'])) -> save($verifyInfo));
			} else {
				$verify -> add($verifyInfo);
			}
			sendVerifyMail($verifyInfo, 3, $userInfo['email']);
			$this -> ajaxReturn('', '验证邮件已发送到您的当前邮箱中，请点击邮件内的验证链接', 0);
		}
		$this -> ajaxReturn('', '请输入您的新邮箱', 1);
	}
}
